import { Context } from 'koa';
import { query, queryOne } from '../database/mysql';
import { User } from '../database/models';
import { hashPassword } from '../utils/password';
import { utils, valids } from '../utils/utils';
import { success, error } from '../utils/response';
import { ResponseCode } from '../config/responseCode';

/**
 * 创建用户（仅管理员）
 */
export async function createUser(ctx: Context): Promise<void> {
  const { username, password, nickname, email, phone, permission_ids } = ctx.request.body as {
    username?: string;
    password?: string;
    nickname?: string;
    email?: string;
    phone?: string;
    permission_ids?: string[];
  };

  if (!username || !password) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户名和密码不能为空');
    return;
  }

  // 保护默认管理员用户名
  if (username.toLowerCase() === 'admin') {
    error(ctx, ResponseCode.FORBIDDEN, 'admin 用户名已被系统保留，不可使用');
    return;
  }

  // 校验邮箱格式
  if (email && !valids.isEmail(email)) {
    error(ctx, ResponseCode.BAD_REQUEST, '邮箱格式不正确');
    return;
  }

  // 校验手机号格式
  if (phone && !valids.isMobile(phone)) {
    error(ctx, ResponseCode.BAD_REQUEST, '手机号格式不正确');
    return;
  }

  // 检查用户名是否已存在
  const existingUser = await queryOne<User>('SELECT * FROM users WHERE username = ?', [username]);
  if (existingUser) {
    error(ctx, ResponseCode.USER_ALREADY_EXISTS);
    return;
  }

  // 加密密码
  const hashedPassword = await hashPassword(password);

  // 创建用户
  const userId = utils.generateUUID();
  await query(
    `INSERT INTO users (id, username, password, nickname, email, phone, is_admin, status)
     VALUES (?, ?, ?, ?, ?, ?, 0, 1)`,
    [userId, username, hashedPassword, nickname || null, email || null, phone || null]
  );

  // 添加权限关系（默认一对一，如果有指定权限）
  if (permission_ids && permission_ids.length > 0) {
    for (const permissionId of permission_ids) {
      const relationId = utils.generateUUID();
      await query(
        'INSERT INTO user_permissions (id, user_id, permission_id) VALUES (?, ?, ?)',
        [relationId, userId, permissionId]
      );
    }
  } else {
    // 如果没有指定权限，可以创建一个默认权限关系（这里需要先有一个默认权限）
    // 暂时跳过，由业务决定
  }

  const newUser = await queryOne<User>('SELECT * FROM users WHERE id = ?', [userId]);
  const { password: _, ...userInfo } = newUser!;
  success(ctx, userInfo);
}

/**
 * 更新用户
 */
export async function updateUser(ctx: Context): Promise<void> {
  const { id, username, password, nickname, email, phone, status, permission_ids } = ctx.request.body as {
    id?: string;
    username?: string;
    password?: string;
    nickname?: string;
    email?: string;
    phone?: string;
    status?: number;
    permission_ids?: string[];
  };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as User;
  // 非管理员只能修改自己的信息
  if (currentUser.is_admin !== 1 && currentUser.id !== id) {
    error(ctx, ResponseCode.PERMISSION_DENIED);
    return;
  }

  const user = await queryOne<User>('SELECT * FROM users WHERE id = ?', [id]);
  if (!user) {
    error(ctx, ResponseCode.USER_NOT_FOUND);
    return;
  }

  // 密码修改权限检查
  if (password !== undefined) {
    // admin用户只能修改自己的密码
    if (currentUser.username === 'admin') {
      if (currentUser.id !== id) {
        error(ctx, ResponseCode.FORBIDDEN, 'admin 用户只能修改自己的密码');
        return;
      }
    } else {
      // 非admin用户：检查是否有系统管理员权限
      // 获取系统管理员权限ID
      const systemAdminPermission = await queryOne<{ id: string }>(
        'SELECT id FROM permissions WHERE code = ?',
        ['SYSTEM_ADMIN']
      );
      
      let hasSystemAdminPermission = false;
      if (systemAdminPermission) {
        // 检查当前用户是否有系统管理员权限
        const permissionCheck = await queryOne<{ id: string }>(
          `SELECT up.id FROM user_permissions up 
           WHERE up.user_id = ? AND up.permission_id = ?`,
          [currentUser.id, systemAdminPermission.id]
        );
        hasSystemAdminPermission = !!permissionCheck;
      }
      
      // 如果没有系统管理员权限，只能修改自己的密码
      if (!hasSystemAdminPermission) {
        if (currentUser.id !== id) {
          error(ctx, ResponseCode.PERMISSION_DENIED, '只有系统管理员可以修改其他用户的密码');
          return;
        }
      }
      // 如果有系统管理员权限，可以修改任何用户的密码（包括admin用户）
    }
  }

  // 保护默认管理员用户：不允许改名
  if (user.username === 'admin' && username !== undefined && username !== 'admin') {
    error(ctx, ResponseCode.FORBIDDEN, 'admin 用户不可改名');
    return;
  }

  // 保护默认管理员用户：不允许禁用
  if (user.username === 'admin' && status !== undefined && status === 0) {
    error(ctx, ResponseCode.FORBIDDEN, 'admin 用户不可禁用');
    return;
  }

  // 更新用户信息
  const updates: string[] = [];
  const params: any[] = [];

  // 密码修改
  if (password !== undefined) {
    const hashedPassword = await hashPassword(password);
    updates.push('password = ?');
    params.push(hashedPassword);
  }

  // 只有管理员可以修改用户名
  if (username !== undefined && currentUser.is_admin === 1) {
    // 再次检查，防止修改 admin 用户名
    if (user.username === 'admin' && username !== 'admin') {
      error(ctx, ResponseCode.FORBIDDEN, 'admin 用户不可改名');
      return;
    }
    // 检查新用户名是否已被其他用户使用
    if (username !== user.username) {
      const existingUser = await queryOne<User>('SELECT * FROM users WHERE username = ? AND id != ?', [username, id]);
      if (existingUser) {
        error(ctx, ResponseCode.USER_ALREADY_EXISTS);
        return;
      }
      // 保护：不能使用 admin 作为用户名
      if (username.toLowerCase() === 'admin') {
        error(ctx, ResponseCode.FORBIDDEN, 'admin 用户名已被系统保留，不可使用');
        return;
      }
      updates.push('username = ?');
      params.push(username);
    }
  }

  if (nickname !== undefined) {
    updates.push('nickname = ?');
    params.push(nickname);
  }
  if (email !== undefined) {
    // 校验邮箱格式
    if (!valids.isEmail(email)) {
      error(ctx, ResponseCode.BAD_REQUEST, '邮箱格式不正确');
      return;
    }
    updates.push('email = ?');
    params.push(email);
  }
  if (phone !== undefined) {
    // 校验手机号格式
    if (!valids.isMobile(phone)) {
      error(ctx, ResponseCode.BAD_REQUEST, '手机号格式不正确');
      return;
    }
    updates.push('phone = ?');
    params.push(phone);
  }
  if (status !== undefined && currentUser.is_admin === 1) {
    // 再次检查，防止禁用 admin 用户
    if (user.username === 'admin' && status === 0) {
      error(ctx, ResponseCode.FORBIDDEN, 'admin 用户不可禁用');
      return;
    }
    updates.push('status = ?');
    params.push(status);
  }

  if (updates.length > 0) {
    params.push(id);
    await query(
      `UPDATE users SET ${updates.join(', ')} WHERE id = ?`,
      params
    );
  }

  // 更新权限关系（仅管理员）
  if (permission_ids !== undefined && currentUser.is_admin === 1) {
    // 如果是 admin 用户，确保始终拥有系统管理员权限
    if (user.username === 'admin') {
      // 获取系统管理员权限ID
      const systemAdminPermission = await queryOne<{ id: string }>(
        'SELECT id FROM permissions WHERE code = ?',
        ['SYSTEM_ADMIN']
      );
      
      if (systemAdminPermission) {
        // 确保 permission_ids 中包含系统管理员权限
        if (!permission_ids.includes(systemAdminPermission.id)) {
          permission_ids.push(systemAdminPermission.id);
        }
      }
    }
    
    // 删除旧权限
    await query('DELETE FROM user_permissions WHERE user_id = ?', [id]);
    
    // 添加新权限
    if (permission_ids.length > 0) {
      for (const permissionId of permission_ids) {
        const relationId = utils.generateUUID();
        await query(
          'INSERT INTO user_permissions (id, user_id, permission_id) VALUES (?, ?, ?)',
          [relationId, id, permissionId]
        );
      }
    }
  }

  const updatedUser = await queryOne<User>('SELECT * FROM users WHERE id = ?', [id]);
  const { password: _, ...userInfo } = updatedUser!;
  success(ctx, userInfo);
}

/**
 * 删除用户（仅管理员）
 */
export async function deleteUser(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户ID不能为空');
    return;
  }

  const user = await queryOne<User>('SELECT * FROM users WHERE id = ?', [id]);
  if (!user) {
    error(ctx, ResponseCode.USER_NOT_FOUND);
    return;
  }

  // 保护默认管理员用户，不允许删除
  if (user.username === 'admin') {
    error(ctx, ResponseCode.FORBIDDEN, 'admin 用户不可删除');
    return;
  }

  // 删除用户权限关系
  await query('DELETE FROM user_permissions WHERE user_id = ?', [id]);
  
  // 删除用户
  await query('DELETE FROM users WHERE id = ?', [id]);

  success(ctx, { message: '删除成功' });
}

/**
 * 查询用户列表（仅管理员）
 */
export async function getUserList(ctx: Context): Promise<void> {
  const { page = 1, pageSize = 10, username, status } = ctx.request.body as {
    page?: number;
    pageSize?: number;
    username?: string;
    status?: number;
  };

  let sql = 'SELECT * FROM users WHERE 1=1';
  const params: any[] = [];

  if (username) {
    sql += ' AND username LIKE ?';
    params.push(`%${username}%`);
  }
  if (status !== undefined) {
    sql += ' AND status = ?';
    params.push(status);
  }

  sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
  const offset = (page - 1) * pageSize;
  params.push(pageSize, offset);

  const users = await query<User>(sql, params);
  const totalResult = await queryOne<{ count: number }>(
    'SELECT COUNT(*) as count FROM users WHERE 1=1' + (username ? ' AND username LIKE ?' : '') + (status !== undefined ? ' AND status = ?' : ''),
    params.slice(0, -2)
  );

  const userList = users.map(user => {
    const { password: _, ...userInfo } = user;
    return userInfo;
  });

  success(ctx, {
    list: userList,
    total: totalResult?.count || 0,
    page,
    pageSize,
  });
}

/**
 * 查询用户详情
 */
export async function getUserDetail(ctx: Context): Promise<void> {
  const { id } = ctx.request.body as { id?: string };

  if (!id) {
    error(ctx, ResponseCode.BAD_REQUEST, '用户ID不能为空');
    return;
  }

  const currentUser = ctx.state.user as User;
  // 非管理员只能查看自己的信息
  if (currentUser.is_admin !== 1 && currentUser.id !== id) {
    error(ctx, ResponseCode.PERMISSION_DENIED);
    return;
  }

  const user = await queryOne<User>('SELECT * FROM users WHERE id = ?', [id]);
  if (!user) {
    error(ctx, ResponseCode.USER_NOT_FOUND);
    return;
  }

  // 获取用户权限
  const permissions = await query(
    `SELECT p.* FROM permissions p
     INNER JOIN user_permissions up ON p.id = up.permission_id
     WHERE up.user_id = ?`,
    [id]
  );

  const { password: _, ...userInfo } = user;
  success(ctx, {
    ...userInfo,
    permissions,
  });
}

